package com.chenglu.android.onelogin;

import android.app.ProgressDialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;


import com.chenglu.android.BuildConfig;
import com.chenglu.android.R;
import com.chenglu.android.bean.LoginBean;
import com.chenglu.android.bean.SmsCodeBean;
import com.chenglu.android.common.base.BaseFullScreenActivity;
import com.chenglu.android.common.net.Constant;
import com.chenglu.android.common.utils.LogUtils;
import com.chenglu.android.common.utils.SPUtils;
import com.chenglu.android.common.utils.ToastUtils;
import com.chenglu.android.mine.login.LoginActivity;
import com.chenglu.android.mine.login.mvp.contract.LoginContract;
import com.chenglu.android.mine.login.mvp.presenter.LoginPresenter;
import com.chenglu.android.onelogin.config.BaseUIConfig;
import com.chenglu.android.onelogin.utils.ExecutorManager;
import com.chenglu.android.onelogin.utils.MockRequest;
import com.google.gson.Gson;
import com.mobile.auth.gatewayauth.AuthRegisterXmlConfig;
import com.mobile.auth.gatewayauth.AuthUIConfig;
import com.mobile.auth.gatewayauth.PhoneNumberAuthHelper;
import com.mobile.auth.gatewayauth.ResultCode;
import com.mobile.auth.gatewayauth.TokenResultListener;
import com.mobile.auth.gatewayauth.annotations.AuthNumber;
import com.mobile.auth.gatewayauth.model.TokenRet;
import com.mobile.auth.gatewayauth.ui.AbstractPnsViewDelegate;


/**
 * 进app直接登录的场景
 */
public class OneKeyLoginActivity extends BaseFullScreenActivity<LoginPresenter> implements LoginContract.View {
    private static final String TAG = OneKeyLoginActivity.class.getSimpleName();

    private EditText mTvResult;
    private PhoneNumberAuthHelper mPhoneNumberAuthHelper;
    private TokenResultListener mTokenResultListener;
    private ProgressDialog mProgressDialog;
    private int mUIType;
    private BaseUIConfig mUIConfig;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mUIType = getIntent().getIntExtra(OneLoginConstant.THEME_KEY, -1);
        setContentView(R.layout.activity_one_login);

        mPresenter= new LoginPresenter();
        mPresenter.attachView(this);


        mTvResult = findViewById(R.id.tv_result);

        //初始化密钥
        sdkInit(BuildConfig.AUTH_SECRET);

        mUIConfig = BaseUIConfig.init(OneLoginConstant.CUSTOM_XML, this, mPhoneNumberAuthHelper);
        oneKeyLogin();
        mTvResult.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                mTvResult.setTextIsSelectable(true);
                mTvResult.setSelectAllOnFocus(true);
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
               // 创建普通字符型ClipData
                ClipData mClipData = ClipData.newPlainText("Label", mTvResult.getText());
               // 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
//                Toast.makeText(OneKeyLoginActivity.this,"登录token已复制", Toast.LENGTH_SHORT).show();
                return false;
            }
        });
    }



    public void sdkInit(String secretInfo) {
        mTokenResultListener = new TokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                hideLoadingDialog();
                if(BuildConfig.NeedLogger){
                    Log.e(TAG, "获取token成功：" + s);
                }
                TokenRet tokenRet = null;
                try {
                    tokenRet = TokenRet.fromJson(s);
                    if (ResultCode.CODE_START_AUTHPAGE_SUCCESS.equals(tokenRet.getCode())) {
                        if(BuildConfig.NeedLogger){
                            Log.i(TAG, "唤起授权页成功：" + s);
                        }
                    }

                    if (ResultCode.CODE_SUCCESS.equals(tokenRet.getCode())) {
                        if(BuildConfig.NeedLogger){
                            Log.i(TAG, "获取token成功：" + s);
                        }

                        //这里去请
//                        mPhoneNumberAuthHelper.get
                        mPresenter.getOneLogin(tokenRet.getToken(), Constant.oneClickLoginByLocalNumber);

//                        getResultWithToken(tokenRet.getToken());
                        mPhoneNumberAuthHelper.setAuthListener(null);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onTokenFailed(String s) {
                if(BuildConfig.NeedLogger){
                    Log.e(TAG, "获取token失败：" + s);
                }
                hideLoadingDialog();
                mPhoneNumberAuthHelper.hideLoginLoading();
                TokenRet tokenRet = null;
                try {
                    tokenRet = TokenRet.fromJson(s);
                    if (ResultCode.CODE_ERROR_USER_CANCEL.equals(tokenRet.getCode())) {
                        //模拟的是必须登录 否则直接退出app的场景
                        finish();
                    } else {
                        finish();
//                        Toast.makeText(getApplicationContext(), "一键登录失败切换到其他登录方式", Toast.LENGTH_SHORT).show();
//                        Intent pIntent = new Intent(OneKeyLoginActivity.this, LoginActivity.class);
//                        startActivityForResult(pIntent, 1002);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mPhoneNumberAuthHelper.quitLoginPage();
                mPhoneNumberAuthHelper.setAuthListener(null);
            }
        };
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(this, mTokenResultListener);
        mPhoneNumberAuthHelper.getReporter().setLoggerEnable(BuildConfig.NeedLogger);
        mPhoneNumberAuthHelper.setAuthSDKInfo(secretInfo);
    }

    /**
     * 进入app就需要登录的场景使用
     */
    private void oneKeyLogin() {
        mPhoneNumberAuthHelper = PhoneNumberAuthHelper.getInstance(getApplicationContext(), mTokenResultListener);
        mPhoneNumberAuthHelper.checkEnvAvailable();
        mPhoneNumberAuthHelper.setProtocolChecked(true);
        mUIConfig.configAuthPage();


//        mPhoneNumberAuthHelper.addAuthRegisterXmlConfig(new AuthRegisterXmlConfig.Builder()
//                .setLayout(R.layout.activity_nice_goods, new AbstractPnsViewDelegate() {
//                    @Override
//                    public void onViewCreated(View view) {
//                        LinearLayout viewById = view.findViewById(R.id.ll_loading_no_data);
//                    }
//                }).build());
        //用户控制返回键及左上角返回按钮效果
        mPhoneNumberAuthHelper.userControlAuthPageCancel();
        //用户禁用utdid
        //mPhoneNumberAuthHelper.prohibitUseUtdid();
        //授权页是否跟随系统深色模式
        mPhoneNumberAuthHelper.setAuthPageUseDayLight(true);

        //授权页物理返回键禁用
        //mPhoneNumberAuthHelper.closeAuthPageReturnBack(true);
        //横屏水滴屏全屏适配
        mPhoneNumberAuthHelper.keepAuthPageLandscapeFullSreen(true);
        //授权页扩大协议按钮选择范围至我已阅读并同意
        mPhoneNumberAuthHelper.expandAuthPageCheckedScope(true);
        getLoginToken(5000);
    }

    /**
     * 拉起授权页
     * @param timeout 超时时间
     */
    public void getLoginToken(int timeout) {
        /*for (int i = 0; i < 2; i++) {
            mPhoneNumberAuthHelper.getLoginToken(this, timeout);
        }*/
        mPhoneNumberAuthHelper.getLoginToken(this, timeout);
        showLoadingDialog("正在唤起授权页");
    }


    public void getResultWithToken(final String token) {

        ExecutorManager.run(new Runnable() {
            @Override
            public void run() {
                final String result = MockRequest.getPhoneNumber(token);
                OneKeyLoginActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //获取到阿里token
                        LogUtils.e("result"+ new Gson().toJson(token));
//                        mTvResult.setText("登陆成功：" + result);
//                        mTvResult.setMovementMethod(ScrollingMovementMethod.getInstance());

                        mPhoneNumberAuthHelper.quitLoginPage();
                        finish();
                    }
                });
            }
        });
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1002) {
            if (resultCode == 1) {
                mTvResult.setText("登陆成功：" + data.getStringExtra("result"));
                mTvResult.setMovementMethod(ScrollingMovementMethod.getInstance());
            } else {
                //模拟的是必须登录 否则直接退出app的场景
                finish();
            }
        }
    }



    public void showLoadingDialog(String hint) {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        }
        mProgressDialog.setMessage(hint);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
    }

    public void hideLoadingDialog() {
        if (mProgressDialog != null) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        mUIConfig.onResume();
    }




    @Override
    public void getLogin(LoginBean bean) {

    }

    @Override
    public void onRefreshLogin(LoginBean bean) {

    }

    @Override
    public void getSmsCode(SmsCodeBean bean) {

    }

    @Override
    public void getOneLogin(LoginBean bean) {
        if (bean.getCode()==Constant.HTTPCODE200) {

            mPhoneNumberAuthHelper.quitLoginPage();
            hideLoadingDialog();
            SPUtils.setString(Constant.AaccessToken, bean.getData().getAccess_token());
//            SPUtils.setString(Constant.AaccessToken, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJyb2xlX25hbWUiOiJ1c2VyIiwidXNlcl9pZCI6IjEwMDAwMDIyIiwidXNlcl9uYW1lIjoiMTUyNzgyMjA1OTgiLCJuaWNrX25hbWUiOiLnlKjmiLcwNTk4Iiwib2F1dGhfaWQiOiIiLCJkZXRhaWwiOnsiaWQiOjEwMDAwMDIyLCJwaWQiOjAsInBwaWQiOjAsInNlbGxlcklkIjowLCJjbGllbnRJZCI6bnVsbCwiYWNjb3VudCI6IlFRU1kwMTMwMiIsIm1vYmlsZSI6IjE1Mjc4MjIwNTk4Iiwibmlja05hbWUiOiLnlKjmiLcwNTk4IiwicmVhbE5hbWUiOm51bGwsImF2YXRhciI6Imh0dHBzOi8vdGVtcGxhdGVmaWxlLnNsbXlrai5jb20vdXBsb2FkLyVFNSVCRSVBRSVFNCVCRiVBMSVFNSU5QiVCRSVFNyU4OSU4N18yMDIzMDEwNTE1NDczMi5wbmciLCJjaGFpbiI6IjAiLCJzYWZlUHdkIjpudWxsLCJzaGFyZUNvZGVVcmwiOiJodHRwczovL3RlbXBsYXRlZmlsZS5zbG15a2ouY29tLzIwMjMwODAxL2Q4MGU4YTQwMTc1NWQ0ZGY1N2VlMWMwM2U0Nzg3N2E0LmpwZyIsIm1lbWJlclNoYXJlQ29kZVVybCI6Imh0dHBzOi8vdGVtcGxhdGVmaWxlLnNsbXlrai5jb20vMjAyMzA5MTEvOWE1OGNmY2MzNmE2NzU5NzFmNzljOTVhM2Q3YjQ2YzcuanBnIiwic3RhdHVzIjoxLCJsZXZlbCI6MCwibW9uZXkiOjAuMCwibW9uZXlUb3RhbCI6MC4wLCJpbnRlZ3JhbCI6MTUuMCwiaW50ZWdyYWxUb3RhbCI6MTUuMCwiYmVhbnMiOjUwLjAsImJlYW5zVG90YWwiOjUwLjAsImNvbGRCZWFucyI6MC4wLCJobWJjIjowLjAsImhtYmNUb3RhbCI6MC4wLCJjcmVkaXQiOjAsIndpdGhkcmF3IjowLjAsImFsaXBheSI6bnVsbCwiYmFuayI6bnVsbCwiYmFua051bWJlciI6bnVsbCwiYmFua1BlcnNvbiI6bnVsbCwiYmFua0FkZHIiOm51bGwsImJhbmtBZGRyRGV0YWlsIjpudWxsLCJpZENhcmQiOm51bGwsImlkQ2FyZEZyb250IjpudWxsLCJpZENhcmRCYWNrIjpudWxsLCJpc0F1dGgiOjAsImlzRW52b3kiOjAsImlzUmVkIjowLCJpc0FjdGl2YXRlIjowLCJjcmVhdGVUaW1lIjoiMjAyMy0wNy0zMSAxMTowNDozMiIsInVwZGF0ZVRpbWUiOiIyMDIzLTA5LTExIDEwOjA2OjA3IiwiaXNEZWxldGVkIjowLCJ2ZXJzaW9uIjo0LCJ0ZW5hbnRSZWRCYWciOjAuMCwicGxhdGZvcm1SZWRCYWciOjAuMH0sInRva2VuX3R5cGUiOiJhY2Nlc3NfdG9rZW4iLCJhY2NvdW50IjoiMTUyNzgyMjA1OTgiLCJjbGllbnRfaWQiOiJ3YXAiLCJleHAiOjE2OTc0MjA1OTgsIm5iZiI6MTY5NjgxNTc5OH0.u2HjmH3dJyhFYYuQZO5N_qFPRmxK3eT2ryJ7YTjDkzc");
            SPUtils.setString(Constant.refreshToken, bean.getData().getRefresh_token());
            SPUtils.setString(Constant.USERNAME, bean.getData().getAccount());
            SPUtils.setBoolean("ISLOGIN", true);
            finish();
        } else {
            ToastUtils.show(bean.getMsg());
        }
    }
}
